package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    private final UserServiceImpl userService;
    private final StringRedisTemplate stringRedisTemplate;
    private final IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query().orderByDesc("liked").page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            queyBlogLiked(blog);
        });

        return Result.ok(records);
    }

    @Override
    public Result queryById(Long id) {
        // 查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        // 查询blog有关用户
        queryBlogUser(blog);

        queyBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result likeblog(Long id) {
        // 1. 获取当前登陆用户
        Long userId = UserHolder.getUser().getId();

        String key = RedisConstants.BLOG_LIKED_KEY + id;

        // 2. 判断当前用户是否点过赞了
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) {
            // 3. 没点过赞
            // 3.1 数据库 like字段+1
            boolean success = update().setSql("liked = liked + 1").eq("id", id).update();
            // 3.2 将用户存入redis中
            if (success) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 4. 点过赞
            // 4.1 数据库like字段-1
            boolean success = update().setSql("liked = liked - 1").eq("id", id).update();
            // 4.2 将用户移除redis
            if (success) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        // 1. 查询top5的点赞用户 redis
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 2. 解析用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 3. 根据用户id查询用户
        String Strids = StrUtil.join(",", ids);
        List<User> users = userService.query().in("id", ids).last("order by field(id," + Strids + ")").list();

        List<UserDTO> userDTO = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());

        // 4. 返回
        return Result.ok(userDTO);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("新增笔记失败！！！");
        }
        // 3. 找到作者的粉丝
        List<Follow> followUserId = followService.query().eq("follow_user_id", user.getId()).list();

        // 4. 推送id给粉丝
        for (Follow follow : followUserId) {
            Long userId = follow.getUserId(); // 粉丝id
            String key = "feed:" + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());

    }

    @Override
    public Result queryBlogFollow(Long max, Integer offset) {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 查询收件箱
        String key = RedisConstants.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typeTUple = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        if (typeTUple == null || typeTUple.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 3. 解析数据 blogId  mintime offset时间戳
        ArrayList<Object> ids = new ArrayList<>(typeTUple.size());
        long mintime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typeTUple) {
            // 获取id
            ids.add(Long.valueOf(tuple.getValue()));
            // 获取分数
            long time = tuple.getScore().longValue();
            if (time == mintime) {
                os++;
            } else {
                mintime = time;
                os = 1;
            }
        }

        // 4. 查blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + idStr + ")").list();


        for (Blog blog : blogs) {
            // 查询博客相关用户
            queryBlogUser(blog);
            // 查询是否被点赞
            queyBlogLiked(blog);
        }

        // 5.封装返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(offset);
        r.setMinTime(mintime);
        return Result.ok(r);
    }

    private void queryBlogUser(Blog blog) {
        Long userID = blog.getUserId();
        User user = userService.getById(userID);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    private void queyBlogLiked(Blog blog) {
        // 1. 获取当前登陆用户
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null) {
            // 用户未登陆无需进行查询
            return;
        }

        Long userId = userDTO.getId();

        // 2. 判断当前用户是否点过赞了
        Double score = stringRedisTemplate.opsForZSet().score(RedisConstants.BLOG_LIKED_KEY + blog.getId(), userId.toString());

        blog.setIsLike(score != null);

    }

}
